import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { ADManagementService } from './admanagement.service';
import { ADManagementDto, CreateUpdateADManagementDto } from './models';
import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared';
import { ToasterService } from '@abp/ng.theme.shared';
import { Subscription } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-admanagement',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, ThemeSharedModule],
  templateUrl: './admanagement.component.html',
  styleUrl: './admanagement.component.scss',
  providers: [ListService]
})
export class ADManagementComponent implements OnInit, OnDestroy {
  adManagement = { items: [], totalCount: 0 } as PagedResultDto<ADManagementDto>;
  createADManagementForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedADManagementId: number;
  isSaving = false;
  Math = Math;

  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1;
  visiblePageNumbers: number[] = [];
  inputPageNumber: number = 1;

  private subscription: Subscription = new Subscription();

  adNumberKeyword = '';
  nameKeyword = '';
  adTypeKeyword = '';
  isSearchMode = false;
  isLoading = false;

  constructor(
    public readonly list: ListService,
    private adManagementService: ADManagementService,
    private fb: FormBuilder,
    private confirmation: ConfirmationService,
    private toaster: ToasterService,
    private modalService: NgbModal
  ) {
    this.createADManagementForm = this.fb.group({
      adManagementUser: ['', [Validators.required, Validators.maxLength(100)]],
      adManagementPerson: ['', [Validators.required, Validators.maxLength(50)]],
      adManagementPhone: ['', [Validators.required, Validators.maxLength(20)]],
      detailedAddress: ['', [Validators.required, Validators.maxLength(200)]],
      province: ['', [Validators.required, Validators.maxLength(50)]],
      adManagementCity: ['', [Validators.required, Validators.maxLength(50)]],
      adManagementDistrict: ['', [Validators.required, Validators.maxLength(50)]],
      defaultAddress: ['', Validators.maxLength(10)],
      available: ['', Validators.maxLength(10)],
      detailedAddressType: ['', Validators.maxLength(50)]
    });
  }

  ngOnInit() {
    this.list.page = 1;
    this.loadData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  loadData() {
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize,
      };
      return this.adManagementService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(
          (response: PagedResultDto<ADManagementDto>) => {
            if (this.isSearchMode) {
              response.items = response.items.filter(item => {
                const adManagementUserMatch = !this.adNumberKeyword.trim() || (item.adManagementUser && item.adManagementUser.toLowerCase().includes(this.adNumberKeyword.trim().toLowerCase()));
                const adManagementPersonMatch = !this.nameKeyword.trim() || (item.adManagementPerson && item.adManagementPerson.toLowerCase().includes(this.nameKeyword.trim().toLowerCase()));
                const detailedAddressTypeMatch = !this.adTypeKeyword.trim() || (item.detailedAddressType && item.detailedAddressType.toLowerCase().includes(this.adTypeKeyword.trim().toLowerCase()));
                return adManagementUserMatch && adManagementPersonMatch && detailedAddressTypeMatch;
              });
            }

            this.adManagement = response;
            if (response.totalCount > 0) {
              this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
              if (this.list.page > this.maxPageCount) {
                this.list.page = this.maxPageCount;
                if (response.items.length === 0) {
                  this.loadDataWithoutCheck();
                }
              }
            } else {
              this.maxPageCount = 1;
              this.list.page = 1;
            }
            this.updateVisiblePageNumbers();
          },
          error => {
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }

  loadDataWithoutCheck() {
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      return this.adManagementService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(
          (response: PagedResultDto<ADManagementDto>) => {
            this.adManagement = response;
            this.updateVisiblePageNumbers();
          },
          error => {
            let errorMessage = '加载数据失败，请稍后重试';
            if (error && error.error && error.error.message) {
              errorMessage = `${errorMessage}: ${error.error.message}`;
            }
            this.toaster.error(errorMessage, '错误', { life: 7000 });
          }
        )
    );
  }

  updateVisiblePageNumbers() {
    const currentPage = this.list.page || 1;
    const pageNumbers = [];
    if (this.maxPageCount <= 5) {
      for (let i = 1; i <= this.maxPageCount; i++) {
        pageNumbers.push(i);
      }
    } else {
      if (currentPage > 3) {
        pageNumbers.push(1, -1);
      }
      let start = Math.max(1, currentPage - 2);
      let end = Math.min(this.maxPageCount, currentPage + 2);
      for (let i = start; i <= end; i++) {
        pageNumbers.push(i);
      }
      if (end < this.maxPageCount) {
        pageNumbers.push(-1, this.maxPageCount);
      }
    }
    this.visiblePageNumbers = pageNumbers;
  }

  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1;
    this.loadData();
  }

  goToPage(page: number) {
    if (page < 1 || page > this.maxPageCount) return;
    this.list.page = page;
    this.loadData();
  }

  onPageInputChange(event: Event) {
    const value = (event.target as HTMLInputElement).value;
    const page = Number(value);
    if (!isNaN(page)) {
      this.inputPageNumber = page;
    }
  }

  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }

  search() {
    this.isSearchMode = true;
    this.list.page = 1;
    this.loadData();
  }

  resetSearch() {
    this.adNumberKeyword = '';
    this.nameKeyword = '';
    this.adTypeKeyword = '';
    this.isSearchMode = false;
    this.list.page = 1;
    this.loadData();
  }

  openCreateModal() {
    this.isModalOpen = true;
    this.isEditMode = false;
    this.createADManagementForm.reset();
    this.createADManagementForm.patchValue({
      adManagementUser: '',
      adManagementPerson: '',
      adManagementPhone: '',
      detailedAddress: '',
      province: '',
      adManagementCity: '',
      adManagementDistrict: '',
      defaultAddress: '初始',
      available: '初始',
      detailedAddressType: ''
    });
  }

  openEditModal(adManagementId: number) {
    this.isModalOpen = true;
    this.isEditMode = true;
    this.selectedADManagementId = adManagementId;
    this.adManagementService.get(adManagementId).subscribe(
      (adManagementData) => {
        this.createADManagementForm.patchValue(adManagementData);
      },
      (error) => {
        this.toaster.error('加载客户地址信息失败', '错误');
        this.closeModal();
      }
    );
  }

  closeModal() {
    this.isModalOpen = false;
    this.createADManagementForm.reset();
    this.createADManagementForm.patchValue({
      adManagementUser: '',
      adManagementPerson: '',
      adManagementPhone: '',
      detailedAddress: '',
      province: '',
      adManagementCity: '',
      adManagementDistrict: '',
      defaultAddress: '',
      available: '',
      detailedAddressType: ''
    }, {emitEvent: false});
  }

  save() {
    if (this.createADManagementForm.invalid) {
      Object.keys(this.createADManagementForm.controls).forEach(key => {
        const control = this.createADManagementForm.get(key);
        control.markAsDirty();
        control.markAsTouched();
      });
      this.toaster.warn('请填写必填字段并修正表单错误', '表单验证');
      return;
    }
    const adManagementData = this.createADManagementForm.value as CreateUpdateADManagementDto;
    this.isSaving = true;
    if (this.isEditMode) {
      this.adManagementService.update(this.selectedADManagementId, adManagementData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createADManagementForm.reset();
          this.loadData();
          this.isSaving = false;
          this.toaster.success('客户地址信息已成功更新', '成功');
        },
        (error) => {
          this.isSaving = false;
          let errorMessage = '更新客户地址信息失败';
          if (error && error.error && error.error.message) {
            errorMessage += ': ' + error.error.message;
          }
          this.toaster.error(errorMessage, '错误');
        }
      );
    } else {
      this.adManagementService.create(adManagementData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createADManagementForm.reset();
          this.loadData();
          this.isSaving = false;
          this.toaster.success('客户地址信息已成功创建', '成功');
        },
        (error) => {
          this.isSaving = false;
          let errorMessage = '创建客户地址失败';
          if (error && error.error && error.error.message) {
            errorMessage += ': ' + error.error.message;
          }
          this.toaster.error(errorMessage, '错误');
        }
      );
    }
  }

  deleteADManagement(adManagementId: number) {
    this.confirmation.warn(
      '确定要删除此客户地址记录吗？',
      '删除确认',
      { messageLocalizationParams: [] }
    ).subscribe((status) => {
      if (status === Confirmation.Status.confirm) {
        this.adManagementService.delete(adManagementId).subscribe(
          () => {
            if (this.adManagement.items.length === 1 && this.list.page > 1) {
              this.list.page--;
            }
            this.loadData();
            this.toaster.success('客户地址记录已成功删除', '成功');
          },
          (error) => {
            let errorMessage = '删除客户地址记录失败';
            if (error && error.error && error.error.message) {
              errorMessage += ': ' + error.error.message;
            }
            this.toaster.error(errorMessage, '错误');
          }
        );
      }
    });
  }
} 